package sharetime.user.controllers;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import sharetime.user.domain.UserData;
import sharetime.util.FileUploadUtils;
import sharetime.web.controllers.BaseController;

@Controller
@RequestMapping("/profilepicture")
public class EditProfilePictureController extends BaseController {

	private Logger logger = LoggerFactory
			.getLogger(EditProfilePictureController.class);

	@RequestMapping(method = RequestMethod.GET)
	public void index(@RequestParam
	long id, HttpServletResponse response) throws IOException {
		UserData ud = userManager.getUserData(id);
		byte[] pic = ud.getProfilePicture();
		if (null == pic) {
			//redirect to default picture location
			response.sendRedirect("");
		} else {
			response.getOutputStream().write(pic);
		}
	}

	@RequestMapping(method = RequestMethod.POST, params = "!_method")
	public String create(HttpServletRequest request) {
		byte[] fileData = FileUploadUtils.handlePictureUpload(request);

		UserData ud = userManager.getUserData(getRemoteUserId());

		ud.setProfilePicture(fileData);

		userManager.updateUserDate(ud);

		return null;
	}

	@RequestMapping(method = RequestMethod.POST, params = "_method=PUT")
	public String update(HttpServletRequest request){
		return null;
	}
	
}
